<?php
namespace plugins\message_push\model;

/**
 * 公众号模板发送
 */
class Official
{
    public function send_official($param)
    {
        $data = [
            'canshu' => [
                'touser' => $param['openid'],
                'template_id' => $param['template_id'],
                'url' => $param['url'],
                'data' => $param['data'],
            ],
        ];
        //根据公司id查询
        $official_config = db('official_config')->where('company_id',$param['company_id'])->find();
        if(empty($official_config)){
            return api_json_echo(false,'请先配置公众号信息');
        }

        $token = $this->getToken($param['company_id'],$official_config['appid'],$official_config['appSecret']);
        //模板消息发送接口
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token;
        $fa = json_encode($data['canshu']);
        $common = new Common();
        $result = $common->https_request($url, $fa);
        return json_decode($result, true);
    }


    //获取access_token的方法。
    public function getToken($company_id,$appid,$appSecret)
    {
        //获取公众号token
        $token = cache('access_token_'.$company_id);
        if (!empty($token)) {
            return $token;
        }
        $common = new Common();
        $TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appSecret;
        $TOKEN_URL = $common->https_request($TOKEN_URL);
        $result = json_decode($TOKEN_URL, true);
        if (isset($result['errcode'])) {
            return api_json_echo(false,$result['errmsg']);
        }
        cache('access_token_'.$company_id, $result['access_token'], 5000);
        return $result['access_token'];
    }

}